/**
 * Created by KL on 2017/1/30.
 */
import { Injectable } from '@angular/core';
import { LoadingController } from 'ionic-angular';
import { Http, RequestOptions, URLSearchParams, Headers } from '@angular/http';
import { AppConfig } from '../app/app.config';
import 'rxjs/add/operator/map';
import { Observable } from 'rxjs/Rx';


const version: string = '1.0.2';
const key: string = 'kalendsoft';
/**
 * Api is a generic REST Api handler. Set your API url first.
 */
@Injectable()
export class Api {
    url: string = AppConfig.getProdUrl();
    loading: any;
    static isLoading: boolean = false;

    constructor(public http: Http, public loadingCtrl: LoadingController) {

    }

    get(endpoint: string, params?: any) {
          if(params==1)
      {
          this.url=AppConfig.getDebugUrl();
      }
        this.openLoading();
    
        // Support easy query params for GET requests
        if (params) {
            let p = new URLSearchParams();
            for (let k in params) {
                p.set(k, params[k]);
            }
            // Set the search field if we have params and don't already have
            // a search field set in options.
        } else {
            params = {};
        }
        //h.append('Version', version);
        var user = (<any>window).User || {};
        endpoint = this.extendEndpoint(endpoint);
        // h.append('token', this.sign(endpoint + key));      
        // h.append('Id', user._id);        

        return  Observable.create(observer => {
            this.http.get(this.url + '/' + endpoint, null).subscribe(data => {
                observer.next(data)
                observer.complete();
                this.closeLoading();
            });
        });
        

    }
    mapjson(url: string, params?: any, options?: RequestOptions) {
        if (!options) {
            options = new RequestOptions();
        }

        this.openLoading();
        if (params) {
            let p = new URLSearchParams();
            for (let k in params) {
                p.set(k, params[k]);
            }
            // Set the search field if we have params and don't already have
            // a search field set in options.
            options.search = !options.search && p || options.search;
        }
        return Observable.create(observer => {
            this.http.get(url, options).subscribe(data => {
                observer.next(data)
                observer.complete();
                this.closeLoading();
            });
        });
    }

    post(endpoint: string, body: any, options?: RequestOptions) {
        let h = new Headers();
        h.append('Content-Type', 'application/json');
        endpoint = this.extendEndpoint(endpoint);
        // h.append('token', this.sign(endpoint + key));  
        if (!options) {
            options = new RequestOptions({
                headers: h,
            });
        }
        return this.http.post(this.url + '/' + endpoint, body, options);
    }

    put(endpoint: string, body: any, options?: RequestOptions) {
        return this.http.put(this.url + '/' + endpoint, body, options);
    }

    delete(endpoint: string, body: any, options?: RequestOptions) {
        return this.http.post(this.url + '/' + endpoint, body, options);
    }

    patch(endpoint: string, body: any, options?: RequestOptions) {
        return this.http.put(this.url + '/' + endpoint, body, options);
    }

    openLoading() {
        if (!Api.isLoading) {
            Api.isLoading = true;
            this.loading = this.loadingCtrl.create({
                spinner: 'dots'
            });

            this.loading.present();
        }
    }
    closeLoading() {
        if (Api.isLoading) {
            Api.isLoading = false;
            this.loading.dismiss();
            // setTimeout(() => { this.loading.dismiss(); }, 500);
        }
    }

    extendEndpoint(endpoint: string) {
        if (endpoint.indexOf('?') >= 0) {
            endpoint += '&&';
        } else {
            endpoint += '?';
        }
        endpoint += 'uuid=' + ((<any>window).UUID || '') + '&timestamp=' + Math.floor(Date.now() / 1000);
        return encodeURI(endpoint);
    }

    sign(endpoint: string) {
        //  return sha1(endpoint);
    }
}
